<?php
namespace app\controller\api;

use app\exception\ErrnoPlus;
use app\service\AccountService;
use app\validate\UserBaseUpdateValidate;
use share\controller\ApiBaseController;
use app\validate\LoginValidate;
use share\exception\ApiException;
use share\exception\Errno;
use share\service\ContextService;
use share\service\UserAuthService;
use share\utils\Helper;

class LoginController extends ApiBaseController{

    protected $beforeActionList = [
        "checkSign",
    ];

    /**
     * @description: 
     * @return {*}
     * @use: 
     */
    public function initValidate(){
        $this->validate = new LoginValidate();
    }

    /**
     * 获取注册验证码
     */
    public function get_register_code_action(){        
        $input = $this->check();
        $package = $this->request->header('pack-name'); 
        $input['packageName'] = $package;
        return self::ok($this->doGetRegisterCode($input));   
    }

     /**
     * 获取注册验证码
     */
    public function get_register_code_v2_action(){        
        $input = $this->check();
        $language = $input['language'];
        if (in_array($language,["zh-CN" ,"zh-TW" , "zh" ,"zh-HK" , "zh-MO"])) {
            $isoCode = "zh-CN";
        } else {
            $isoCode = "en-US";
        }
        $input['isoCode'] = $isoCode;
        return self::ok($this->doGetRegisterCode($input));
    }

    
     /**
     * 获取注册验证码
     */
    public function get_register_code_v3_action(){        
        $input = $this->check();
        $language = $input['language'];
        if (in_array(strtolower($language),["zh-cn" ,"zh-tw" , "zh" ,"zh-hk" , "zh-mo"])) {
            $isoCode = "zh-CN";
        } else {
            $isoCode = "en-US";
        }
        $input['isoCode'] = $isoCode;
        return self::ok($this->doGetRegisterCode($input));
    }

    /**
     * 获取注册验证码
     */
    public function get_register_code_v4_action(){        
        $input = $this->check();
        $language = $input['language'];
        if (in_array(strtolower($language),["zh-cn" ,"zh-tw" , "zh" ,"zh-hk" , "zh-mo",'cn'])) {
            $isoCode = "zh-CN";
        } else {
            $isoCode = "en-US";
        }
        $param = $this->request->param();
        $input['isoCode'] = $isoCode;
        $input['account'] = isset($param['phone']) ? $param['phone'] : $param['email'];
        if(isset($param['phoneCode'])){
            $input['phoneCode'] = $param['phoneCode'];
        }
        return self::ok($this->doGetRegisterCode($input));
    }

    /**
     * 注册
     */
    public function register_action(){
        $input = $this->check();
        $param = $this->request->param();
        if(isset($param['location'])){
            $input['location'] = $param['location'];
        }
        else{
            if(isset($param['isoCode'])){
                $input['location'] = $param['isoCode'];
            }
            else{
                throw new ApiException("lost isoCode or location data",ErrnoPlus::PARAM_ERROR);
            }
        }
        $input['unencodePass'] = true;//密码明文
        return self::ok($this->doRegister($input));
    }

    /**
     * 注册
     */
    public function register_v2_action(){

        $input = $this->check();
        $input['unencodePass'] = true;//密码明文
        return self::ok($this->doRegister($input));
    }
    
    /**
     * 注册
     */
    public function register_v3_action(){
        $input = $this->check();
        return self::ok($this->doRegister($input));
    }

    /**
     * 注册
     */
    public function register_v4_action(){
        $input = $this->check();
        $param = $this->request->param();  
        $input['vendor'] = ContextService::getVendor();
        $input['account'] = isset($param['phone']) ? $param['phone'] : $param['email'];
        $input['phoneCode'] = isset($param['phoneCode']) ? $param['phoneCode'] : '';
        return self::ok($this->doRegister($input));
    }

   

    /**
     * 获取重置密码的验证码
     */
    public function get_reset_code_action(){
        $input = $this->check(); 
        $input['vendor'] = ContextService::getVendor();
        $packageName = $this->request->header("pack-name");
        if(empty($packageName)){
            $input['packageName'] = 'com.antsvision.seeeasy';//老版本默认使用seeEasy
            $input['sendmailVendor'] = 'ENZ';
        }
        else{
            $input['packageName'] = $packageName;
        }
        $isocode = $input['isoCode'];
        if ($isocode === "CN" || $isocode === "HK" || $isocode === "MO" || $isocode === "TW") {
            $language = "zh-CN";
        } else {
            $language = "en-US";
        }
        $input['language'] = $language;
        return self::ok($this->doGetResetCode($input));
    }

    /**
     * 获取重置密码的验证码
     */
    public function get_reset_code_v2_action(){
        $input = $this->check();
        $input['vendor'] = ContextService::getVendor();
        $input['packageName'] = ContextService::getPackageName();
        return self::ok($this->doGetResetCode($input));
    }

    /**
     * 用户重置密码
     */
    public function reset_pswd_action(){
        $input = $this->check();
        $input['vendor'] = ContextService::getVendor();
        return self::ok(AccountService::resetPassword($input));
    }

    /**
     * 用户重置密码v2
     */
    public function reset_pswd_v2_action(){
        $input = $this->check();
        $input['passwordEncode'] = true;
        $input['vendor'] = ContextService::getVendor();
        return self::ok(AccountService::resetPassword($input));
    }


    /**
     * 绑定账号 获取验证码
     */
    public function send_bind_code_action(){
        $input = $this->check();
        $param = $this->request->param();  
        $input['accessToken'] = isset($param['accessToken']) ? $param['accessToken'] : '';
        UserAuthService::checkLoginType($input['loginType']);      
        if(isset($input['email']) && strpos($input['email'],'@') !== false){
            $res = AccountService::sendCodeBindAccountByEmail($input['email'],$input,ContextService::getVendor(),ContextService::getPackageName());
        }
        else if(isset($input['phone'])){
            $res = AccountService::sendCodeBingAccountByPhone($input['phone'],$input,ContextService::getIP(),ContextService::getVendor(),ContextService::getPackageName());
        }
        else{
            throw new ApiException("lost account info");
        }
        return self::ok($res);
        
    }

    /**
     * 第三方账号绑定手机号/邮箱
     */
    public function binding_account_action(){
        $input = $this->check();
        $phoneCode = $this->request->param('phoneCode');
        UserAuthService::checkLoginType($input['loginType']);
        if(!empty($phoneCode)){
            $input['phoneCode'] = intval($phoneCode);
        }
        else{
            $input['phoneCode'] = 86;
        }
        $res = AccountService::bindingAccount($input,ContextService::getVendor());
        return self::ok($res);
    }

    /**
     * 通过手机号/邮箱获取登录验证码
     */
    public function send_login_code_action(){
        $input = $this->check();
        $input['vendor'] = ContextService::getVendor();
        $email = $this->request->param('email');
        $phone = $this->request->param('phone');
        $ip = ContextService::getIP();
        $data = null;
        if(!empty($email)){
            if(!Helper::checkEmailFormat($email)){
                throw new ApiException("email format error",ErrnoPlus::EMAIL_FORMAT);
            }
            $data = AccountService::sendLoginCodeByEmail($email,$input,ContextService::getVendor(),ContextService::getPackageName());
        }
        else if(!empty($phone)){
            $input['phoneCode'] = $this->request->param('phoneCode');
            $data = AccountService::sendLoginCodeByPhone($phone,$input,$ip,ContextService::getVendor(),ContextService::getPackageName());
        }
        return self::ok($data);
    }


    protected function doRegister($input){
        $vendor = ContextService::getVendor();
        $input['vendor'] = $vendor;
        $account = $input['account'];
        $account = strtolower($account);// 账号信息统一小写
        $isChinaPhone = false;
        if(isset($input['language']) && $input['language'] === 'zh-CN' ){
            $isChinaPhone = true;
        }
        if(isset($input['phoneCode']) && intval($input['phoneCode']) ===  86 ){
            $isChinaPhone = true;
        }
        if(isset($input['isoCode']) && $input['isoCode'] ===  'CN' ){
            $isChinaPhone = true;
        }
        self::checkAccountFormat($account,$isChinaPhone);
        if(strpos($account,'@') !== false){//邮箱获取验证码  
            $data = AccountService::registerByEmail($account,$input);
        }
        else{//短信获取   
            if(!$isChinaPhone){//
                throw new ApiException("No longer supports register by phone number",ErrnoPlus::PHONE_FORMAT);  
            }    
            $data = AccountService::registerByPhone($account,$input);
        }
        return $data;
    }

    protected function doGetRegisterCode($input){
        $ip = ContextService::getIp();
        $vendor = ContextService::getVendor();
        $packageName = ContextService::getPackageName();
        $input['vendor'] = $vendor;
        $input['packageName'] = $packageName;
        $account = $input['account'];
        $account = strtolower($account);
        $isChinaPhone = false;
        if(isset($input['language']) && $input['language'] === 'zh-CN' ){
            $isChinaPhone = true;
        }
        if(isset($input['phoneCode']) && $input['phoneCode'] ===  86 ){
            $isChinaPhone = true;
        }
        if(isset($input['isoCode']) && $input['isoCode'] ===  'CN' ){
            $isChinaPhone = true;
        }
        self::checkAccountFormat($account,$isChinaPhone);
        if(strpos($account,'@') !== false){//邮箱获取验证码  
            $data = AccountService::getRegisterCodeByEmail($account,$input,$vendor,$packageName);
        }
        else{//短信获取
            if(!$isChinaPhone){//
                throw new ApiException("No longer supports register by phone number",ErrnoPlus::PHONE_FORMAT);  
            }
            $data = AccountService::getRegisterCodeByPhone($account,$input,$ip,$vendor,$packageName);
        }
        return $data;
    }


    protected function doGetResetCode($input){
        $ip = ContextService::getIp();
        $vendor = ContextService::getVendor();
        $input['vendor'] = $vendor;
        $account = $input['account'];
        $account = strtolower($account);
        $isChinaPhone = isset($input['language']) && $input['language'] === 'zh-CN' ? true : false;
        self::checkAccountFormat($account,$isChinaPhone);
        if(strpos($account,'@') !== false){//邮箱获取验证码 
            $data = AccountService::getResetCodeByEmail($account,$input,ContextService::getVendor(),ContextService::getPackageName());
        }
        else{//短信获取
            $data = AccountService::getResetCodeByPhone($account,$input,$ip,ContextService::getVendor(),ContextService::getPackageName());
        }
        return $data;
    }

    public static function checkAccountFormat($account,$isChinaPhone = false){
        if(strpos($account,'@') !== false){//邮箱获取验证码            
            if(!Helper::checkEmailFormat($account)){
                throw new ApiException("email format error",ErrnoPlus::EMAIL_FORMAT);
            }
        }
        else{//短信获取
            if($isChinaPhone){
                if(!Helper::checkChinaPhone($account)){
                    throw new ApiException("phone format error",ErrnoPlus::PHONE_FORMAT);
                }
            }
            else{  // 账号格式简单排查
                if(!Helper::checkSimplePhone($account)){
                    throw new ApiException("phone format error",ErrnoPlus::PHONE_FORMAT);
                }
            }
        }
    }

}
